<script lang="ts" setup>
import { ref, onUnmounted } from 'vue'
import sx from './components/sx.vue'
import gz from './components/gz.vue'
import pl from './components/pl.vue'
import {
    Avatar,
    Tag,
    Tabs,
    TabPane,
    Button,
    InputSearch,
    Modal,
    UploadDragger,
    message,
    Empty,
    Badge
} from 'ant-design-vue'
import { PageApi } from './use/api'
import { Row, Col } from 'ant-design-vue'
import WxChat from './components/wx.vue'
const obj = ref({
    type: 0,
    id: 0,
    avatarUrl: '',
    username: ''
})
const handlePrivateMessage = (type: number, id: number, avatarUrl?: string, username?: string) => {
    obj.value = {
        type: type,
        id: id,
        avatarUrl: avatarUrl || '',
        username: username || ''
    }
}
const activeTag: any = ref(1)
/**
 * 正常用户点击
 */
const handleZxClick = () => {
    activeTag.value = 1
    getUser()
}
/**
 * 异常用户点击
 */
const handleAbnormalClick = () => {
    activeTag.value = 2
    getAbnormalUserList()
}
/**
 * 获取异常用户列表
 */
const abnormalList = ref<any[]>([])
const getAbnormalUserList = async (text?: string) => {
    const res = await PageApi.getAbnormalList({
        page: 1,
        limit: 9999,
        username: text || ''
    })
    if (res.length > 0) {
        abnormalList.value = res
    }
}
const activeKey = ref('user')
// 分页参数
const params = ref({
    page: 1,
    limit: 10,
    username: ''
})
const userList = ref<any[]>([])
const getUser = async () => {
    const res = await PageApi.getPageList({
        ...params.value
    })
    if (obj.value.type === 0 && res.length > 0) {
        message.warning('默认加载第一个账户的私信列表')
        obj.value = {
            type: 1,
            id: res[0].id,
            avatarUrl: res[0].avatarUrl || '',
            username: res[0].username || ''
        }
    }
    userList.value = res
}
// 初始化获取正常用户列表
getUser()
// 获取异常用户列表
getAbnormalUserList()
const onSearch = (value: string) => {
    if (activeKey.value === 'user') {
        if (activeTag.value === 1) {
            if (!value) {
                getUser()
                return false
            }
            let list = userList.value.filter((item: any) => item.username.includes(value))
            userList.value = list
        } else {
            if (!value) {
                getAbnormalUserList()
                return false
            }
            let list = abnormalList.value.filter((item: any) => item.username.includes(value))
            abnormalList.value = list
        }
    }
}
/**
 * 获取聊天消息列表
 */
// 定时器
const timer = ref<any>(null)
const chatInfo: any = ref({})
const sessionList = ref<any[]>([])
const getSessionList = async () => {
    const res = await PageApi.getSessionList({})
    sessionList.value = res
    if (!chatInfo.value.id) {
        chatInfo.value = res[0]
    }
}
// 轮询
const isGet = ref<boolean>(false)
timer.value = setInterval(async () => {
    if (isGet.value) {
        return false
    }
    isGet.value = true
    const res = await PageApi.getSessionList({})
    if (res) {
        isGet.value = false
    }
    sessionList.value = res
}, 5000)
/**
 * 处理聊天窗口点击
 * @param item
 */
const handleChatIm = (item: any) => {
    chatInfo.value = item
}
// 在组件卸载时清除定时器
onUnmounted(() => {
    if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
    }
})
const handleTabClick = () => {
    console.log(activeKey.value)
    if (activeKey.value === 'user') {
        getUser()
    } else {
        getSessionList()
    }
}

const objFile: any = ref({})
const logObj: any = ref({})
async function handleOk() {
    if (objFile.value?.name) {
        const res = await PageApi.upload({ file: objFile.value })
        logObj.value = res
        if (res.batchNumber) {
            message.success('上传成功')
            params.value.username = ''
            getUser()
            open.value = false
        } else {
            message.error('上传失败')
        }
    }
}
const open = ref(false)
const fileList = ref([])
const handleUpload = async (file: any, fileList: any) => {
    logObj.value = {}
    fileList = fileList
    objFile.value = file
    return false
}
</script>

<template>
    <Page>
        <Row>
            <Col :span="5">
                <div class="pl-3">
                    <div class="bg-card btn-header mt-4 p-3 pt-4">
                        <Tabs
                            class="bg-card"
                            v-model:activeKey="activeKey"
                            @change="handleTabClick"
                        >
                            <TabPane tab="账号列表" key="user"> </TabPane>
                            <TabPane tab="聊天窗口" key="im"> </TabPane>
                        </Tabs>
                        <InputSearch
                            v-if="activeKey === 'user'"
                            class="mb-4"
                            placeholder="搜索账号"
                            enter-button
                            @search="onSearch"
                        />
                        <div v-if="activeKey === 'user'">
                            <Tag color="green" @click="handleZxClick"
                                >在线({{ userList.length }})</Tag
                            >
                            <Tag color="cyan">离线(0)</Tag>
                            <Tag color="purple" @click="handleAbnormalClick"
                                >异常({{ abnormalList.length }})</Tag
                            >
                            <Tag @click="getUser">刷新列表</Tag>
                            <Button class="mt-3" @click="open = true">导入邮箱</Button>
                        </div>
                    </div>
                    <div
                        v-if="activeKey === 'user'"
                        class="demo-loadmore-list bg-card p-3 pb-5"
                        style="height: calc(100vh - 300px); overflow-y: auto"
                    >
                        <div
                            v-for="item in activeTag === 1 ? userList : abnormalList"
                            :key="item.id"
                            class="relative mb-3 flex"
                        >
                            <Avatar :size="64" :src="item.avatarUrl" />
                            <div class="ml-2">
                                <div class="text-lg font-bold">账号名：{{ item.username }}</div>
                                <div class="text-sm text-gray-500">昵称：{{ item.name }}</div>
                                <div class="text-sm text-gray-500">备注：{{ item.mark }}</div>
                                <div style="margin-left: -6px; padding-top: 6px">
                                    <Badge :dot="item.isRedDot"
                                        ><Button
                                            type="link"
                                            size="small"
                                            @click="
                                                handlePrivateMessage(1, item.id, item.avatarUrl)
                                            "
                                            >私信:{{ item.privateMessageNum }}</Button
                                        ></Badge
                                    >
                                    <Button
                                        type="link"
                                        size="small"
                                        @click="handlePrivateMessage(2, item.id, item.avatarUrl)"
                                        >评论:{{ item.commentNum }}</Button
                                    >
                                    <Button
                                        type="link"
                                        size="small"
                                        @click="
                                            handlePrivateMessage(3, item.uid, '', item.username)
                                        "
                                        >粉丝:{{ item.followers }}</Button
                                    >
                                </div>
                            </div>
                            <div class="ml-auto" style="position: absolute; right: 0">
                                <Tag :color="activeTag === 1 ? 'green' : 'purple'">{{
                                    activeTag === 1 ? '在线' : '异常'
                                }}</Tag>
                            </div>
                        </div>
                    </div>
                    <!-- 聊天窗口列表 -->
                    <div
                        v-else
                        class="demo-loadmore-list bg-card cursor-pointer p-3 pb-5"
                        style="height: calc(100vh - 300px); overflow-y: auto;margin-top: -30px;"
                    >
                        <div
                            v-for="item in sessionList"
                            :key="item.id"
                            @click="handleChatIm(item)"
                            :class="`mb-3 flex hover:bg-gray-100 ${item.id === chatInfo.id ? 'bg-gray-100' : ''}`"
                        >
                            <Badge :dot="item.isRedDot"
                                ><Avatar :size="64" :src="item.formAvatarUrl"
                            /></Badge>
                            <div class="ml-2">
                                <div class="text-lg font-bold">账号名：{{ item.formUsername }}</div>
                                <div class="text-sm text-gray-500">昵称：{{ item.formName }}</div>
                                <div style="margin-left: -6px; padding-top: 6px">
                                    <Button type="text" size="small"
                                        >关注:{{ item.formFollowing }}</Button
                                    >
                                    <Button type="text" size="small"
                                        >粉丝:{{ item.formFollowers }}</Button
                                    >
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </Col>
            <!-- 右侧内容 -->
            <Col :span="19">
                <sx
                    v-if="obj?.type === 1 && activeKey === 'user'"
                    :id="obj?.id"
                    :avatarUrl="obj?.avatarUrl"
                    :key="`sx-${obj.id}`"
                />
                <pl
                    v-else-if="obj?.type === 2 && activeKey === 'user'"
                    :id="obj?.id"
                    :avatarUrl="obj?.avatarUrl"
                    :key="`pl-${obj.id}`"
                />
                <gz
                    v-else-if="obj?.type === 3 && activeKey === 'user'"
                    :id="obj?.id"
                    :dqUserName="obj?.username"
                    :key="`gz-${obj.id}`"
                />
                <div
                    v-else-if="activeKey === 'im' && sessionList.length > 0 && chatInfo.id"
                    class="p-3"
                >
                    <WxChat
                        :avatar-url="chatInfo?.avatarUrl"
                        :chat-info="chatInfo"
                        :type="1"
                        :key="chatInfo.id"
                        :open="activeKey === 'im' && sessionList.length > 0"
                    />
                </div>
                <Empty style="margin-top: 300px" v-else />
            </Col>
        </Row>
        <Modal v-model:open="open" title="账号导入" @ok="handleOk">
            <UploadDragger
                v-model:fileList="fileList"
                name="file"
                :multiple="true"
                :maxCount="1"
                :directory="false"
                :accept="'.xls,.xlsx'"
                :beforeUpload="handleUpload"
            >
                <p class="ant-upload-drag-icon">
                    <inbox-outlined></inbox-outlined>
                </p>
                <p class="ant-upload-text">上传导入文件</p>
                <p class="ant-upload-hint">文件格式xls，xlsx</p>
            </UploadDragger>
            <div v-if="logObj.failureLogList && logObj.failureLogList.length">
                <div class="text-red-500">导入失败数量"{{ logObj.failureNum }}"原因：</div>
                <ul>
                    <li v-for="item in logObj.failureLogList" :key="item.username">{{ item }}</li>
                </ul>
                <div style="color: greenyellow">导入成功数量{{ logObj.successNum }}</div>
                <ul>
                    <li v-for="item in logObj.successLogList" :key="item.username">{{ item }}</li>
                </ul>
            </div>
        </Modal>
    </Page>
</template>
<style scoped lang="scss">
.btn-header {
    .ant-tag {
        margin-bottom: 15px;
        cursor: pointer;
    }
}
</style>
